package com.sun.decode;

import com.alibaba.fastjson2.JSON;
import com.sun.config.GlobalVariableConfig;
import com.sun.handler.MyWebSocketHandler;
import com.sun.pojo.PushEntity;
import com.sun.pojo.WsJobEntity;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

import static com.sun.constants.Constant.WS_JOB_DATA;

@Slf4j
public class SqlDecode implements Job {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    @Autowired
    private GlobalVariableConfig globalVariableConfig;

    @Override
    public void execute(JobExecutionContext context) {
        WsJobEntity wsJob = (WsJobEntity) context.getMergedJobDataMap().get(WS_JOB_DATA);
        if(globalVariableConfig.getSessionCount() > 0) {
            String sqlScript = wsJob.getSqlScript();
            List<Map<String, Object>> sqlResult = jdbcTemplate.queryForList(sqlScript);
            PushEntity pushData = new PushEntity();
            pushData.setType(wsJob.getType());
            pushData.setData(sqlResult);
            myWebSocketHandler.broadcastMessage(wsJob.getType(), JSON.toJSONString(pushData));
        }
    }

}
